package com.yc.vote.servlet;

import com.yc.common.bean.Result;
import com.yc.common.biz.BizException;
import com.yc.common.servlet.BaseServlet;
import com.yc.vote.entity.Items;
import com.yc.vote.entity.Record;
import com.yc.vote.entity.User;
import com.yc.vote.entity.Vote;
import com.yc.vote.mapper.VoteMapper;
import com.yc.vote.service.impl.RecordServiceImpl;
import com.yc.vote.service.impl.VoteServiceImpl;
import com.yc.vote.util.MyBatisHelper;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

/**
 * 实现一个Servlet 响应多个请求
 */
@WebServlet("/record/*") // * 表示 0~n 字符 用于匹配多个地址
public class RecordServlet extends BaseServlet {
    private RecordServiceImpl biz = new RecordServiceImpl();
    // 要把 protected 改成 public
    // /vote/save.s
    public Result commit(HttpServletRequest request, HttpServletResponse response){
        String vid = request.getParameter("vid");
        String[] iids = request.getParameterValues("iid");
        Object o = request.getSession().getAttribute("loginedUser");
        User user = (User)o;
        if (user!=null){
            // 未登录
            // return Result.failure("请先登录系统", null);
            // TODO 后续完成登录之后，再屏蔽下面的代码
            user = new User();
            user.setId(1);
        }
        List<Record> records = new ArrayList<>();
        if (iids!=null){
            for (String iid : iids){
                Record record = new Record();
                record.setVid(Integer.parseInt(vid));
                record.setIid(Integer.parseInt(iid));
                record.setUsid(user.getId());
                records.add(record);
            }
        }
        try {
            biz.commit(records);
            return Result.success("投票成功", null);
        } catch (BizException e){
            e.printStackTrace();
            return Result.failure(e.getMessage(), null);
        }

    }
}
